#!/usr/bin/env python2.7
VERSION = '1.0.0.1'

import os
import sys
import shlex
import traceback

import autoutils
from autoutils import COLOR
from autoutils import OptParser

class autosniffdetect:

    def __init__(self):

        self.version = VERSION
        self.nopen = autoutils.autoutils()
        self.parser = self.get_arg_parser()
        self.doprint = self.nopen.doprint


    def main(self, argv):

        prog = argv[0]
        argv = argv[1:]
        opts, args = self.nopen.parseArgs(self.parser, argv)

        # connect to autoport after parse args
        if not self.nopen.connected:
            self.nopen.connect()

        if opts.v:
            self.print_version(prog)
            return

        # Linux build kernels.....
        if "Linux" not in self.nopen.nopen_serverinfo:
            self.nopen.doprint(self.nopen.COLOR_FAILURE, 'BAIL: -gs sniffdetect is not supported on this:\n\n\n%s\n' % self.nopen.nopen_serverinfo)
            return self.nopen.finish()
        output, nopenlines, outputlines = self.nopen.doit('/usr/bin/which lsof 2>/dev/null')
        output2, nopenlines2, outputlines2 = self.nopen.doit('ls -la /proc/net/packet 2>/dev/null')
        if not output or not output2:
            self.nopen.doprint(self.nopen.COLOR_FAILURE, 'Bail: -gs sniffdetect requires lsof and /proc/net/packet...\n\nYou should still investigate any sniffers that could be present with:\ncat /proc/net/packet\n')
            return self.nopen.finish()
         # Lets find the SOCKET active processes within /proc/net/packet   


        
        output1, nopenlines1, outputlines1 = self.nopen.doit('/bin/cat /proc/net/packet')
        inode_list = []  
        # Make a list of the inodes associated with possible sniffers
    
        for line in outputlines1[1:]:
            inode_list.append(line.split()[8])
    
        i = 0
        warn = ''    
        if not inode_list:
            self.nopen.doprint(self.nopen.COLOR_SUCCESS, 'Looks like you have no sniffers!')
        else:
            for inode in inode_list:
                print inode_list[i]
                output2, nopenlines2, outputlines2 = self.nopen.doit('lsof 2>/dev/null | egrep "%s"' % inode_list[i])
                warn += output2+'\n'
                i = i + 1
            mylist = []
            for line in warn.splitlines():
                mylist.append(line.split()[1])
                finallist = ','.join(mylist)

            self.nopen.textpopup('-geometry 128x48 -bg white -fg red', 'We might have possible sniffers on this box!! \n %s\n\n\nYou should think about running lsof on these guys!!\nThat is if lsof exists on this box.\n\nlsof -Pnp \"%s\"\n' % (warn,finallist))
        

        # Free BSD not implemented yet.
        return self.nopen.finish()


    def get_arg_parser(self):

        epilog = '\n-gs sniffdetect version %s\nThis will detect wether or not a process is utilizing a socket\n' % self.version

        parser = OptParser(usage='usage: -gs sniffdetect [options]', epilog=epilog)
        parser.add_option('-v', dest='v', action='store_true', help='Show version and exit.')
        return parser

    def print_version(self, prog):
        script_name = os.path.basename(prog)

        if script_name.startswith('auto'):
            script_name = script_name.split('auto', 1)[1]

        self.doprint('-gs %s version %s' % (script_name, self.version))


if __name__ == '__main__':

    try:
        # re-set the argv b/c NOPEN will do weird things with splitting args
        argv = shlex.split(' '.join(sys.argv))
        autosniffdetect().main(argv)
    except Exception, e:
        print '\n\n%sUnhandled python exception: %s%s\n\n' % \
            (COLOR['bad'], str(e), COLOR['normal'])
        print '%sStack trace:\n' % COLOR['fail']
        traceback.print_exc()
        print COLOR['normal']
